package cluster

import (
	"context"
	"encoding/json"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
	"xgame.go_server/comm/log"
)

// StartDiscoverNewBizServer 开始发现新的业务服务器,
// 通过 Etcd 的 watch 指令监听 "xgame.go_server/biz_server" 为前缀的所有关键字的变化
func StartDiscoverNewBizServer(
	etcdEndpointArray []string, onFind func(*BizServerData)) {
	if nil == etcdEndpointArray ||
		len(etcdEndpointArray) <= 0 {
		return
	}

	etcdCli, err := clientv3.New(clientv3.Config{
		Endpoints:   etcdEndpointArray,
		DialTimeout: 5 * time.Second,
	})

	if nil != err {
		log.Error("%+v", err)
		return
	}

	go func() {
		watchChan := etcdCli.Watch(context.TODO(), "xgame.go_server/biz_server", clientv3.WithPrefix())

		for resp := range watchChan {
			for _, event := range resp.Events {
				switch event.Type {
				case 0: // PUT
					serverData := &BizServerData{}
					_ = json.Unmarshal(event.Kv.Value, serverData)

					// 连接到业务服务器
					ok := connToBizServer(serverData)

					if ok &&
						nil != onFind {
						onFind(serverData)
					}
				case 1: // DELETE
				}
			}
		}
	}()
}
